(function(){
    function LazyImage(options){
        options = options || {} 
        let defaults = {
            context:document,
            attr:'lazy-image',
            threshold:1,
            speed:300,
            callback:Function.prototype
        }
        return new LazyImage.prototype.init(Object.assign(defaults,options))
    }
    LazyImage.prototype={
        constructor:LazyImage,
        init:function init(config){
            // 把信息挂在实例上，其它方法中，基于实例即可获取这些信息
            this.config = config
            this.imageBoxList = []
            // 创建监听器
            const oboptions = {threshold:[config.threshold]}
            this.ob = new IntersectionObserver(changes =>{
                changes.forEach(item =>{
                    let {
                        isIntersecting,
                        target
                    }= item
                    if(isIntersecting){
                        this.singHandle(target)
                        this.ob.unobserve(target)
                    }
                })
            },oboptions)
            this.observeAll()
        },
        // 单张图片的延迟加载
        singHandle:function singHadle(imgBox){
            console.log(imgBox)
            let config = this.config,
            imgObj = imgBox.querySelector('img'),
            trueImg = imgObj.getAttribute(config.attr);
            imgObj.src= trueImg
            console.log(trueImg)
            imgObj.onload=()=>{
                imgObj.style.transition = `opacity${config.speed}ms`
                imgObj.style.opacity = 1
                // 回调函数->插件的生命周期函数[回调函数&发布订阅]
                config.callback.call(this,imgObj)
            }
        },
        // 监听需要的DOM元素
        observeAll(){
            let config = this.config,
            allImages = config.context.querySelectorAll(`img[${config.attr}]`);
            [].forEach.call(allImages,(item) =>{
                let imageBox = item.parentNode;
                // if(this.refresh() && this.imageBoxList.include(imageBox)){return}
                this.imageBoxList.push(imageBox)
                console.log(this.imageBoxList)
                this.ob.observe(imageBox)
            }) 
        },
        refresh:function refresh(){
            // this.ob.observe(true)
            return true
        }
    }
    LazyImage.prototype.init.prototype = LazyImage.prototype;

    if(typeof window!=='undefind'){
        window.LazyImage = LazyImage
    }
    if(typeof module==='object'&& typeof module.exports === 'obejct'){
        module.exports = LazyImage
    }
})()